<template>
	<view id='user_add'>
		<view class="userType c-flex jc-between c-item-center">
			<view >
				用户类型
			</view>
			
			<view class="tabs-con c-flex c-flex-row jc-between">
				<view class="tab-item" v-for="(item,index) in tabsArr" :key="index" @click="onCheckTabbarClick(item)"
				    :class="{'selected':item.selected}">	
					{{item.label}}
				</view>
			</view>
		</view>
		<view class="d_input">
			<view class="d_input_item  c-flex c-item-center jc-between">
				<view class="personnel_num">客户名称</view>
				<view class="my_input c-flex  c-item-center">
					<input placeholder="请输入客户名称" type="text" placeholder-class='placeholderClass'
						:maxlength="15"
						v-model="fromObj.name" />
					
				</view>

			</view>
			<view class="bottom_border"></view>
			<view class="d_input_item  c-flex c-item-center jc-between">
				<view class="personnel_num">联系电话</view>
				<view class="my_input c-flex  c-item-center">
					<input placeholder="请输入联系电话" type="number" :maxlength="11" placeholder-class='placeholderClass'
						 v-model="fromObj.phone" />
					
				</view>
			
			</view>
			<view class="bottom_border"></view>
			<view class="d_input_item  c-flex c-item-center jc-between">
				<view class="personnel_num">身份证号</view>
				<view class="my_input c-flex  c-item-center">
					<input placeholder="请输入身份证号" type="text" :maxlength="18" placeholder-class='placeholderClass'
						 v-model="fromObj.idCard" />
					
				</view>

			</view>
			<view class="bottom_border"></view>
			<view class="d_input_item  c-flex c-item-center jc-between">
				<view class="personnel_num">所属地区</view>
				<view class="my_input c-flex  c-item-center"  @tap="chooseVillagerHandlder()">
					<input placeholder="请选择所属小区" type="text" disabled="" placeholder-class='placeholderClass'
						v-model="area" />
					<image src="@/static/images/index/right-icon.png"></image>
				</view>
			
			</view>
			<view class="bottom_border"></view>
			<view class="d_input_item  c-flex c-item-center jc-between">
				<view class="personnel_num">详细地址</view>
				<view class="my_input c-flex  c-item-center" >
					<input placeholder="请输入详细地址" type="text"  placeholder-class='placeholderClass'
						v-model="fromObj.address" />
					
				</view>

			</view>
			
		</view>
		<view class="phone_panel" v-if="tabBarItem && tabBarItem.value !==0">
			<view class="title">上传营业执照</view>
			<view class="c-flex jc-between">
				<view class="view_phone" v-for="(item,index) in sceneImgList">
					<image class="closeBtn" :src='remoteImgCommonUrl+"close@2x.png"' @tap.stop="delImg(index,'scene')"></image>
					<image :src="item" @tap.stop='previewFile(index,sceneImgList)'></image>
				</view>
				
				<view class="add_phone" @tap='upload_image()' v-if='sceneImgList.length<1'>
					<image src="@/static/images/common/sm-capture-img.png"></image>
					<view>上传营业执照</view>
				</view>
				<view class="view_phone" style="height: 205rpx;">
					
					<image :src="imgUrl+'legend.png'" @tap.stop='previewFile(0,[imgUrl+"legend.png"])'></image>
				</view>
			</view>
			
		</view>
		<view class="submit_btn">
			<view class="submit" @tap="submit()">确定</view>
			<!-- <view class="delete" v-if="editType==='edit'" @tap="deleteBtn()">删除</view> -->
		</view>
		<tydPrompt ref='tydPrompt' sureBtnColor="#E86748" :content="content" @confirmPrompt='confirmPrompt'></tydPrompt>
		<selectVillage ref='villPrompt' :userType='userType' :townId='townId' :villageIndex='fromObj.villageId' :townIndex='townIndex' :townList="townList" @addDataPrompt='addUserInfo'></selectVillage>
	</view>
</template>

<script>
	import {
		aliOssParams
	} from '@/utils/oss/oss.js';
	import tydPrompt from '@/components/tyd-prompt/tyd-prompt.vue';
	import selectVillage from '@/components/select-village/select-village.vue'
	import {
		toast,
		checkPositiveIntegers,
		validateCreditCode,
		isValidIdNumber,
		isValidPhone
	} from '@/utils/utils.js';
	export default {
		components: {
			selectVillage,tydPrompt
		},
		data() {
			
			return {
				sceneImgList: [],
				attachments:'',
				url: 'https://tyd-worksite.oss-cn-beijing.aliyuncs.com',
				remoteImgCommonUrl: this.$API.IMG_URL + '/tower-install/',
				content: '是否确认删除此用户信息？',
				tabBarItem:null,
				tabsArr:[{label:'民用',value:0},{label:'商业',value:1},{label:'工业',value:2}],
				imgUrl: this.$API.IMG_URL + '/liquefied-mall/common/',
				indicatorStyle: `height: 50px;line-height:50px;`,
				fromObj: {
					id:'',
					villageId: '',
					address: '',
					name: null,
					phone: null,
					type: '',
					idCard: '',
					licensePic:''
				},
				area:'',
				streetName:'',
				latitude:'',
				longitude:'',
				townList:[],
				editType:'',
				townIndex:'',
				userType:'energy-app'
				
			};
		},
		onLoad(params) {
			
			this.editType = params.type;
			uni.setNavigationBarColor({
				backgroundColor:'#fff',
				frontColor: '#000000'
			});
			uni.setNavigationBarTitle({
				title:this.editType==='edit'?'编辑用户':''
			})
			this.tabsArr.forEach(item=>{
				item['selected'] = false;
			});
			const userInfo = JSON.parse(uni.getStorageSync('member'))
			this.fromObj.phone = userInfo.mobile;
			if(this.editType==='edit'){
				const data = JSON.parse(params.item);
				this.fromObj.id = data.id;
				this.fromObj.name = data.name;
				this.fromObj.phone = data.phone;
				this.fromObj.idCard = data.idCard;
				this.streetName =  data.street;
				this.area = data.street+'/'+data.villageName;
				this.fromObj.address  =data.address;
				this.fromObj.villageId = data.villageId;
				this.tabBarItem = this.tabsArr[data.type]
				this.sceneImgList.push(data.licensePic)
			}else{
				this.tabBarItem = this.tabsArr[0]
			}
			
			this.tabBarItem.selected = true;
			this.fromObj.type = this.tabBarItem.value;
			this.getLiquefiedGasTownList()
		},
		
		methods: {
			getLiquefiedGasTownList(){
				this.$API.liquefiedGasTownList(this.userType,{page:1,limit:999}).then(res=>{
					let arr = res.page.list||[]
					
					this.townList = arr ;
					this.townIndex = this.townList.findIndex((item) => item.name === this.streetName);
					
				})
			},
			onCheckTabbarClick(item){
				if(this.editType==='edit') return
				
				this.tabBarItem.selected = false;
				item.selected = true;
				this.tabBarItem = item;		
				this.fromObj.type = item.value;
			},
			getCurrAddr() {
				let that = this;
				this.qqmapsdk.reverseGeocoder({
					success: function(res) { //成功后的回调
						let data = res.result.address_reference.landmark_l1 || res.result.address_reference
							.landmark_l2;
						console.log('当前位置:', data)
						//that.curr_address = data.title || '腾渊达集团';
						that.latitude = data.location.lat;
						that.longitude = data.location.lng;
					},
					fail: function(error) {
						toast(error);
					},
					complete: function(res) {
						//console.log(res);
					}
				})
			},
			chooseVillagerHandlder(){
				this.$refs.villPrompt.open();
			},
			addUserInfo(obj){
				this.streetName =  obj.streetName;
				this.area = obj.streetName+'/'+obj.villageName;
				this.fromObj.villageId = obj.villageId;
				this.townIndex = this.townList.findIndex((item) => item.name === this.streetName);
				
			},
			chooseAddrhandlder() {
				let that = this;
				uni.chooseLocation({
					latitude: this.latitude,
					longitude: this.longitude,

					success: function(res) {
						that.area = res.address;
						console.log('res：', res);
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					}
				});
			},
			deleteBtn(){
				this.$refs.tydPrompt.open();
				
			},
			confirmPrompt() {
				this.$API.liquefiedGasUserAppDelete([this.fromObj.id]).then(res => {
					if (res.code === 0) {
						toast('操作成功')
						setTimeout(() => {
							uni.navigateBack();
							
						}, 500)
				
					}
				})
			},
			submit() {

				if (this.requestStatus) {
					return
				}
				this.requestStatus = true;
				setTimeout(() => {
					this.requestStatus = false;
				}, 2000)
				if (!this.fromObj.name) {
					toast('请填写用户名');
					return;
				}
				
				if (!isValidPhone(this.fromObj.phone)) {
					toast('请输入正确的手机号码');
					return;
				} 
				// if (!isValidIdNumber(this.fromObj.idCard)) {
				// 	toast('请输入正确的身份证号码');
				// 	return;
				// } 
				if (!this.fromObj.villageId) {
					toast('请填写所属小区');
					return;
				}
				if(this.tabBarItem.value !==0 && this.sceneImgList.length===0){
					toast('请上传营业执照');
					return
				}
				this.fromObj.licensePic = this.sceneImgList.toString();
				this.saveInfo();
			},
			
			saveInfo(obj) {
				this.$API.liquefiedGasUserAppSave(this.fromObj,this.editType).then(res => {
					if (res.code === 0) {
						toast('操作成功')
						setTimeout(() => {
							uni.navigateBack();
							this.requestStatus = false;
						}, 500)

					}
				})
			},
			delImg(idx) {
			
				
					this.sceneImgList.splice(idx, 1);
				 
			},
			upload_image() {
				let that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album','camera'], //从相册选择
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						const tempFilePaths = res.tempFilePaths;
						that.imgList = res.tempFilePaths;
						console.log(that.imgList)
						for (let i = 0; i < tempFilePaths.length; i++) {
							that.getAccessInfo(tempFilePaths[i]);
						}
					}
				});
			
			
			
			},
			previewFile(index, imgArr) {
				uni.previewImage({
					current: index, //预览图片的下标
					urls: imgArr, //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
					loop: true,
					indicator: 'default'
				});
			},
			getAccessInfo(filePath) {
				this.$API.getAccessInfo('iot-app-auth').then(res => {
					if (res.code == 0) {
						var accessInfo = res.data;
						const {
							accessKeySecret,
							accessKeyId,
							expiration,
							securityToken
						} = accessInfo;
						var obj = aliOssParams(accessKeyId, accessKeySecret, expiration, securityToken, this.url,
							'png', 'image/tyd-worksite/gas/');
						if (obj) {
							this.uploadProgress(filePath, obj);
						} else {
							toast('数据错误，请重新上传');
						}
					}
			
				})
			},
			
			uploadProgress(filePath, obj) {
				let that = this;
				uni.showLoading({
					title: '上传中...',
					icon: 'none'
				})
			
				const uploadTask = uni.uploadFile({
					url: obj.host,
					filePath: filePath,
					name: 'file',
					formData: {
						'key': obj.fileName,
						'policy': obj.policy,
						'OSSAccessKeyId': obj.aid,
						'signature': obj.signature,
						'x-oss-security-token': obj.securityToken,
						'success_action_status': '200'
			
					},
					success: function(uploadFileRes) {
						console.log(uploadFileRes);
						if (uploadFileRes.statusCode == 200) {
			
							let imgUrl = that.url + '/' + obj.fileName;
			
							
								that.sceneImgList.push(imgUrl);
							
			
							uni.hideLoading()
							toast('上传成功');
						} else {
							toast('上传失败');
							uni.hideLoading()
						}
			
					},
					fail(err) {
						console.log('error:', err);
						toast('上传失败');
						uni.hideLoading()
						//that.$refs.popup.close();
					}
				});
			
				
			
			}
			
		}
	}
</script>
<style>
	.uni-button-color {
		color:#E86748 !important;
	}

	page {
		height: 100%;
		background: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	

	#user_add {
		padding: 14rpx 32rpx 32rpx 32rpx;
		.userType{
			background: #FFFFFF;
			border-radius: 25rpx;
			padding: 30rpx;
			position: relative;
			top: 20rpx;
			
		}
		.tabs-con{
			width:65%;
			.tab-item{
				background: #FFFFFF;
				border-radius: 27rpx;
				font-family: PingFang-SC, PingFang-SC;
				font-weight: 400;
				font-size: 26rpx;
				color: #3E3E3E;
				padding: 10rpx 28rpx;
				position: relative;
				
				
			}
			.selected{
				font-weight: 400;
				font-size: 26rpx;
				color: #FFFFFF;
				background: linear-gradient( 180deg, #F18858 0%, #E86547 100%);
				border-radius: 27rpx;
			}
		}
		.phone_panel {
			//margin-top: 32rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			gap: 42rpx;
			padding: 26rpx 20rpx;
			    margin: 40rpx 0;
				.title{
					font-family: PingFang-SC, PingFang-SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 26rpx;
				}
			.view_phone {
				width: 310rpx;
				height: 200rpx;
				border-radius: 10rpx;
				position: relative;
		
				//margin:48rpx 34rpx;
				image {
		
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}
		
				.closeBtn {
					width: 32rpx;
					height: 32rpx;
					position: absolute;
					top: 5rpx;
					right: 4rpx;
				}
			}
		
			.add_phone {
				width: 300rpx;
				height: 200rpx;
				border-radius: 10rpx;
				border: 2rpx dashed #D2D2D2;
				//margin:48rpx 34rpx;
				text-align: center;
		
				image {
					margin-top: 55rpx;
					width: 40rpx;
					height: 42rpx;
				}
		
				view {
					font-size: 20rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #9B9B9B;
				}
		
			}
		}
		.submit_btn {

			position: fixed;
			bottom: 50rpx;
			left: 50%;
			transform: translate(-50%,-50%);
			view{
				margin: 0 auto;
				width: 710rpx;
				height: 84rpx;
				font-family: PingFang-SC, PingFang-SC;
				font-weight: 500;
				font-size: 28rpx;
				
				line-height: 84rpx;
				text-align: center;
				border-radius: 16rpx;
			}
			.submit {
				background: linear-gradient( 180deg, #F18858 0%, #E86547 100%);
				color: #FFFFFF;
			}
			.delete{
				margin-top: 25rpx;
				color: #E86748;
				border: 2rpx solid #E96949;
				
			}
		}

		
		

		.d_input {
			background: #FFFFFF;
			border-radius: 20rpx;
			//font-size: 28rpx;

			margin: 40rpx auto 0;

			.d_input_item {

				width: 686rpx;
				height: 100rpx;
				margin: 0 26rpx 0 30rpx;

				image {
					width: 20px;
					height: 20px;
					right: 29px;
					position: absolute;
				}

				.my_input {
					
					width: 500rpx;
				}
			}

			.personnel_num {
				width: 500rpx;
				padding-left: 0rpx;
				font-size: 28rpx;
				font-family: PingFang-SC-Medium, PingFang-SC;
				font-weight: 400;
				color: #000;
			}



			input {

				border: 0;
				padding: 0;
				outline: none;
				text-align: right;
				padding-right: 60rpx;
				font-size: 28rpx;
				padding-right: 90rpx;width: 500rpx;
				
			}

			/deep/.placeholderClass {
				font-size: 14px;
				
			}
		}

		.bottom_border {
			width: 622rpx;
			height: 2rpx;
			margin: 0 auto;
			background-color: #F7F7F7;
		}
	}
</style>